import os
import sys
import traceback
from PyQt6.QtGui import QIcon, QPixmap
from PyQt6.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,
                             QPushButton, QFileDialog, QLineEdit, QLabel, QTextEdit, QCheckBox, QGridLayout,
                             QHBoxLayout)
from PyQt6.QtCore import QThread, pyqtSignal, QDateTime, QByteArray, QBuffer, QIODevice, QSettings
from xml.etree import ElementTree as ET

icon_data = "..."  # 省略了原始图标数据以节省空间

# 全局变量存储原始的 ElementTree
original_tree = None


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle('LINK114查询')
        self.setGeometry(100, 100, 750, 600)
        self.setup_icon()
        self.setup_ui()
        self.load_config()

    def setup_icon(self):
        icon_bytes = QByteArray.fromBase64(icon_data.encode('utf-8'))
        icon_buffer = QBuffer()
        icon_buffer.setData(icon_bytes)
        icon_buffer.open(QIODevice.OpenModeFlag.ReadOnly)
        pixmap = QPixmap()
        pixmap.loadFromData(icon_buffer.data())
        icon = QIcon(pixmap)
        self.setWindowIcon(icon)

    def setup_ui(self):
        layout = QVBoxLayout()

        # 文件路径部分
        file_path_layout = QVBoxLayout()
        self.file_path_label = QLabel('选择要查询的域名TXT:')
        file_path_layout.addWidget(self.file_path_label)
        self.file_path_input = QLineEdit()
        file_path_layout.addWidget(self.file_path_input)

        self.browse_button = QPushButton('浏览')
        self.browse_button.clicked.connect(self.browse_file)
        file_path_layout.addWidget(self.browse_button)

        layout.addLayout(file_path_layout)

        # 账号密码输入框
        account_password_layout = QHBoxLayout()
        account_label = QLabel('账号:')
        account_password_layout.addWidget(account_label)
        self.account_input = QLineEdit()
        self.account_input.setText('1003206180')
        account_password_layout.addWidget(self.account_input)

        password_label = QLabel('密码:')
        account_password_layout.addWidget(password_label)
        self.password_input = QLineEdit()
        self.password_input.setText('1003206180')
        account_password_layout.addWidget(self.password_input)


        layout.addLayout(account_password_layout)

        # 开始按钮
        self.start_button = QPushButton('开始')
        self.start_button.clicked.connect(self.start_scraping)
        layout.addWidget(self.start_button)

        # 控制台输出
        self.console_output = QTextEdit()
        self.console_output.setReadOnly(True)
        layout.addWidget(self.console_output)

        # 添加新布局 - 复选框
        self.checkboxes_layout = QGridLayout()
        layout.addLayout(self.checkboxes_layout)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

    def load_config(self):
        global original_tree  # 使用全局变量来保存原始的 ElementTree
        # 加载配置文件
        config_path = "../../Config/config.xml"
        original_tree = ET.parse(config_path)  # 保存原始的 ElementTree
        root = original_tree.getroot()
        for idx, element in enumerate(root.findall('element')):
            name = element.find('name').text
            enabled = element.find('enabled').text == "true"
            checkbox = QCheckBox(name)
            checkbox.setChecked(enabled)
            checkbox.stateChanged.connect(
                lambda state, cb=checkbox, el=element: self.on_checkbox_state_changed(state, cb, el))
            row = idx // 5  # 假设每行5个复选框
            col = idx % 5  # 假设每行5个复选框
            self.checkboxes_layout.addWidget(checkbox, row, col)

    def on_checkbox_state_changed(self, state, checkbox, element):
        # 当复选框状态改变时，更新 XML 文件
        enabled = state == 2  # Qt.Checked == 2
        element.find('enabled').text = str(enabled).lower()
        try:
            # 使用全局变量中的原始 ElementTree
            tree = original_tree
            tree.write("../../Config/config.xml", encoding="UTF-8", xml_declaration=True)
            # self.log(f'{checkbox.text()} 的状态被更改为: {enabled}')
        except Exception as e:
            error_message = f"Error updating the configuration file: {str(e)}"
            self.log(error_message)
            with open('error_log.txt', 'a', encoding='utf-8') as log_file:
                log_file.write(error_message + '\n')
                log_file.write(traceback.format_exc() + '\n')

    def browse_file(self):
        file_path, _ = QFileDialog.getOpenFileName(self, "选择TXT文件", "", "TXT Files (*.txt)")
        if file_path:
            self.file_path_input.setText(file_path)

    def log(self, message):
        timestamp = QDateTime.currentDateTime().toString()
        self.console_output.append(
            f'<span style="color:blue;">[{timestamp}]</span> <span style="color:black;">{message}</span>')

    def start_scraping(self):
        file_path = self.file_path_input.text()  # 要查询的文件路径
        username = self.account_input.text()
        password = self.password_input.text()
        self.log(file_path)
        self.log(username)
        self.log(password)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.log('账密为空默认一次查询500条')
    main_window.log('会员账号一次查询2000条')
    main_window.show()
    sys.exit(app.exec())
